package com.ee.chat.admin.service2.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ee.chat.admin.service2.IImAnalysisService;
import com.ee.chat.admin.service.IOperationService;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.UserImAnalysisMapper;
import com.ee.chat.common.entity.UserImAnalysis;
import com.ndhutu.ee.util.DateUtil;
import com.ndhutu.ee.util.StringUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @Author AppiJ
 * @Date 2020/12/3 15:00
 */
@Service
public class ImAnalysisServiceImpl implements IImAnalysisService {

    @Resource
    UserImAnalysisMapper imAnalysisMapper;
    @Resource
    IOperationService operationService;

    @Override
    public Result list(HttpServletRequest request, Integer userId, Integer host, String field, String sort,
                       String time, Integer page, Integer limit) throws Exception {
        Map<String, Object> data = new HashMap<>();

        if(StringUtil.isEmpty(time) && userId == null){
            HttpSession session = request.getSession(true);
            List<String> userPermissions = (List<String>)session.getAttribute("userPermissions");
            if(!userPermissions.contains("/dataStatis/imAnalysis/viewList")){
                data.put("datas", new ArrayList<>());
                data.put("total", 0);

                return Result.returnSuccess(data);
            }
        }

        String beginDate = null, endDate = null;
        if(!StringUtil.isEmpty(time)){
            String[] arr = time.split(" - ");
            beginDate = arr[0];
            endDate = arr[1];
        }else{
            beginDate = DateUtil.format(new Date(), "yyyy-MM-dd");
        }

        if(field == null){
            field = "totalNum";
            sort = "desc";
        }
        Page<UserImAnalysis> p = new Page<>(page, limit);
        IPage<List<Map<String, Object>>> iPage = imAnalysisMapper.list(p, userId, host, field, sort, beginDate, endDate);

        data.put("datas", iPage.getRecords());
        data.put("total", iPage.getTotal());

        operationService.addOperationLog(request, "获取消息分析列表数据");

        return Result.returnSuccess(data);
    }
}
